package com.tm.util;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ServletUtilsEx {

	private static Log logger = LogFactory.getLog(ServletUtilsEx.class);

	public static void renderJson(HttpServletResponse response, Object object) {
		String jsonpCallback = null;//客户端请求参数
		try {
//			jsonpCallback = new String(ServletHolderFilter.getContext().getRequest().getParameter("jsonpCallback"));//客户端请求参数
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		if(jsonpCallback ==null || jsonpCallback.isEmpty()){
			ServletUtilsEx.render(response, JSONUtilsEx.serialize(object), "text/plain;charset=UTF-8");
		}else{
			ServletUtilsEx.render(response, jsonpCallback+"("+JSONUtilsEx.serialize(object)+")", "text/plain;charset=UTF-8");
		}
		//jsonpCallback = null;
	}

	public static void render(HttpServletResponse response, String text, String contentType) {
		try {
			response.setContentType(contentType);
			response.getWriter().write(text);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
	}

	public static void renderText(HttpServletResponse response, String text) {
		try {
			response.setContentType("text/plain;charset=UTF-8");
			response.getWriter().write(text);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
	}
}
